package com.sduept.nwld.dataserver.controller.base.secondary;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;

import org.apache.commons.lang3.StringUtils;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.NodeExpandEvent;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.TreeNode;
import org.primefaces.model.UploadedFile;
import org.springframework.beans.factory.annotation.Autowired;

import com.sduept.bigdata.fault.manager.WaveFileAssistManager;
import com.sduept.bigdata.fault.manager.WaveFileManager;
import com.sduept.bigdata.fault.system.properties.FaultSystemProperties;
import com.sduept.bigdata.weather.map.MapDataCache;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.cim.exception.WaveFileGetException;
import com.sduept.cim.model.core.Substation;
import com.sduept.cim.model.extend.CfgAnalogChannel;
import com.sduept.cim.model.extend.CfgDigitalChannel;
import com.sduept.cim.model.extend.WaveFile;
import com.sduept.cim.model.extend.wave.dmf.DmfAlarm;
import com.sduept.cim.model.generation.GeneratingUnit;
import com.sduept.cim.model.generation.HydroGeneratingUnit;
import com.sduept.cim.model.protection.ProtectionEquipment;
import com.sduept.cim.model.protection.WaveEquipment;
import com.sduept.cim.model.wires.ACLineSegment;
import com.sduept.cim.model.wires.Breaker;
import com.sduept.cim.model.wires.BusbarSection;
import com.sduept.cim.model.wires.Compensator;
import com.sduept.cim.model.wires.PowerTransformer;
import com.sduept.cim.model.wires.TransformerWinding;
import com.sduept.cim.query.service.SubstationQueryService;
import com.sduept.cim.wave.service.CfgConfigureManager;
import com.sduept.cim.wave.service.DmfCreateManager;
import com.sduept.cim.wave.service.WaveEquipmentManager;
import com.sduept.core.entity.IdentifiedObject;
import com.sduept.generator.ObjectId;
import com.sduept.nwld.dataserver.manager.cim.BxCimManager;
import com.sduept.nwld.dataserver.manager.cim.CimManager;
import com.sduept.nwld.dataserver.model.edata.cim.bx.BxSubstation;
import com.sduept.nwld.dataserver.util.LibTreeNode;
import com.sduept.nwld.wave.util.CfgChnsParserUtil;
import com.sduept.utils.PingYinUtil;

import lombok.extern.slf4j.Slf4j;

//@ManagedBean
//@ViewScoped
@Slf4j
@ViewScoped
@Named
public class WaveEquipmentController extends AbstractController {

	/**
	 *
	 */
	private static final long serialVersionUID = 7259152911176984562L;

	@Autowired
	private CimManager manager;
	@Autowired
	private MapDataCache cimChe;
	@Autowired
	private CfgConfigureManager cfgMan;
	@Autowired
	private DmfCreateManager dmfManager;
	@Autowired
	private WaveFileManager waveFilemanager;
	@Autowired
	private WaveEquipmentManager weManager;
	@Autowired
	private BxCimManager bxcim;
	@Autowired
	private WaveFileAssistManager wfam;
	@Autowired
	private SubstationQueryService substationManager;
	@Autowired
	private FaultSystemProperties pros;

	private CfgAnalogChannel ca = null;

	private CfgDigitalChannel cd = null;

	private TreeNode root;
	private TreeNode currentSelect;
	private String filterStation;
	private String svgContent;
	private CfgAnalogChannel analogSelected = new CfgAnalogChannel();
	private List<CfgAnalogChannel> analogSelecteds = new ArrayList<CfgAnalogChannel>();
	private CfgDigitalChannel digitSelected = new CfgDigitalChannel();
	private List<CfgDigitalChannel> digitSelecteds = new ArrayList<CfgDigitalChannel>();
	private List<CfgAnalogChannel> anologInfo = new ArrayList<>();
	private List<CfgDigitalChannel> digitInfo = new ArrayList<>();
	private List<String> equipmentNames = new ArrayList<>();
	public Map<String, List<String>> digitRelateDevice = new HashMap<>();
	private String stationId;
	private String waveId;
	private WaveEquipment selectedWaveEquipment;
	private List<WaveFile> waveFiles = new ArrayList<>();
	private String dmfMsg;
	private List<WaveEquipment> waveEquipments = new ArrayList<>();
	private WaveEquipment selectWaveEquipment;
	private WaveEquipment preWaveEquipment = new WaveEquipment();
	private int rowsCounts = 0;
	private Map<String, byte[]> uploadFileMap = new HashMap<>();
	private StreamedContent file;

	public static final String FILE_FORMAT_CFG = "cfg";
	public static final String FILE_FORMAT_DAT = "dat";

	private int voltage = 500;

	@PostConstruct
	public void init() {
		initTree();
	}

	public void autoGenarate() {
		if (currentSelect != null && currentSelect.getData() instanceof WaveEquipment) {
			WaveEquipment wave = (WaveEquipment) currentSelect.getData();
			try {
				cfgMan.reGenerateWaveChannels(wave);
				// dmfManager.createDmf(wave.getId());
				getWaveChannelInfo(waveId);
				// getMsgs(wave.getId());
			} catch (WaveFileGetException e) {
				addErrorMessage("未找到录波配置文件" + e.fileName);
			}
		}
	}

	public void relationEquipment() {
		if (currentSelect != null && currentSelect.getData() instanceof WaveEquipment) {
			WaveEquipment wave = (WaveEquipment) currentSelect.getData();
			try {
				cfgMan.relationEquipment(wave);
				getWaveChannelInfo(waveId);
			} catch (Exception e) {
				addErrorMessage("更新出错：" + e.getMessage());
			}
			addSuccessMessage("更新通道成功");
		}
	}

	public void resetgAnalogChannel() {
		for (CfgAnalogChannel channel : analogSelecteds) {
			channel.setEquipmentId(null);
			channel.setEquipmentName(null);
			channel.setEquipmentType(null);
			cfgMan.saveCfgAnalogChannel(channel);
		}
		addSuccessMessage("重置通道成功！");
	}

	public void resetgDigitalChannel() {
		for (CfgDigitalChannel channel : digitSelecteds) {
			channel.setEquipmentId(null);
			channel.setEquipmentName(null);
			channel.setEquipmentType(null);
			cfgMan.saveCfgDigitalChannelChannel(channel);
		}
		addSuccessMessage("重置通道成功！");
	}

	public void createDmf() {
		if (currentSelect != null && currentSelect.getData() instanceof WaveEquipment) {
			WaveEquipment wave = (WaveEquipment) currentSelect.getData();
			dmfManager.createDmf(wave.getId());
			getMsgs(wave.getId());
			updateWaveEquipment();
			addSuccessMessage("生成dmf文件成功！");
		} else {
			addErrorMessage("无法生成dmf文件！");
		}

	}

	public void createCfg() {
		if (currentSelect != null && currentSelect.getData() instanceof WaveEquipment) {
			WaveEquipment we = (WaveEquipment) currentSelect.getData();
			try {
				we.setCfg(cfgMan.getWaveCfgConent(we));
				weManager.saveWaveEquipment(we);
				addSuccessMessage("成功生成cfg文件!");
			} catch (Exception e) {
				e.printStackTrace();
				addErrorMessage("生成cfg失败!");
			}
		} else {
			addErrorMessage("无法生成cfg文件！");
		}
	}

	public void initTree() {
		root = new DefaultTreeNode();
		List<Substation> stations = new ArrayList<>();
		stations = substationManager.listStationsByVoltage(voltage);
		Collections.sort(stations, new Comparator<Substation>() {
			@Override
			public int compare(Substation o1, Substation o2) {
				return PingYinUtil.getPingYin(o1.getName()).compareTo(PingYinUtil.getPingYin(o2.getName()));
			}
		});
		genStationTreeNode(stations);
	}

	public void generteAll() {
		cfgMan.deleteAllCfgChanne();
		List<Substation> stations = cimChe.getS500List();
		for (Substation station : stations) {
			List<WaveEquipment> list = weManager.findByStationId(station.getId());
			for (WaveEquipment wave : list) {
				try {
					cfgMan.generateWaveChannels(wave);
					dmfManager.createDmf(wave.getId());
				} catch (WaveFileGetException e) {
					e.printStackTrace();
					continue;
				}
			}
		}
		testInfo();
		addSuccessMessage("所有设备生成成功！");
	}

	public void testInfo() {
		List<Substation> stations = cimChe.getS500List();
		StringBuilder sb = new StringBuilder();
		for (Substation station : stations) {
			sb.append(station.getName() + "\n");
			String report = cfgMan.generateProtectionReport(station.getId());
			sb.append(report);
		}
		writeStringToFile("subStationEquipment.log", sb.toString());
	}

	public void writeStringToFile(String filePath, String s) {
		try {
			FileOutputStream fos = new FileOutputStream(filePath);
			fos.write(s.getBytes("UTF-8"));
			fos.close();
			// OutputStreamWriter oStreamWriter = new OutputStreamWriter(new
			// FileOutputStream(filePath), "utf-8");
			// oStreamWriter.append(s);
			// oStreamWriter.close();
			log.info("完成");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void genStationTreeNode(List<Substation> stations) {
		for (Substation s : stations) {
			new LibTreeNode("station", s, root);
		}
	}

	public void filterTree(String name) {
		root = new DefaultTreeNode();
		List<Substation> roots = manager.getStationByName(name);
		genStationTreeNode(roots);
	}

	public void onNodeExpand(NodeExpandEvent event) {
		TreeNode node = event.getTreeNode();
		node.getChildren().clear();
		if ("station".equals(node.getType())) {
			Substation station = (Substation) node.getData();
			List<WaveEquipment> list = weManager.findByStationId(station.getId());
			for (WaveEquipment wave : list) {
				new LibTreeNode("wave", wave, node);
			}
		}
	}

	public void onNodeSelect(NodeSelectEvent event) {
		currentSelect = event.getTreeNode();
		waveEquipments.clear();
		if ("station".equals(currentSelect.getType())) {
			Substation sub = (Substation) currentSelect.getData();
			genSvgContent(sub.getId());
			List<WaveEquipment> list = weManager.findByStationId(sub.getId());
			waveEquipments.addAll(list);
			// selectedSid = sub.getId();
			waveId = null;
			getAllUnboundEquipmentNames(sub.getId());
			// cfgMan.generateProtectionReport(sub.getId());
		} else {
			svgContent = "1";
			WaveEquipment wave = (WaveEquipment) currentSelect.getData();
			stationId = wave.getSubId().toString();
			waveId = wave.getId();
			getWaveChannelInfo(waveId);
			selectedWaveEquipment = wave;
			waveFiles = waveFilemanager.listWaveFiles(selectedWaveEquipment.getId());
			getMsgs(waveId);
		}
	}

	/**
	 * 重新生成dmf以后，更新所选择的WaveEquipment信息
	 */
	private void updateWaveEquipment() {
		if(selectedWaveEquipment==null) {
			addErrorMessage("请选择录波装置");
			return;
		}
		selectedWaveEquipment = weManager.getWaveEquipment(selectedWaveEquipment.getId());
	}

	private void getWaveChannelInfo(String waveId) {
		// 根据id获取模拟通道和数字通道
		anologInfo = cfgMan.listCfgAnalogChannelsByWaVeId(waveId);
		digitInfo = cfgMan.listCfgDigitalChannelsByWaVeId(waveId);
	}

	private void getMsgs(String waveId) {
		dmfMsg = "";

		List<DmfAlarm> list = dmfManager.listDmfAlarmByWaveId(waveId);
		for (DmfAlarm alarm : list) {
			if (!StringUtils.isEmpty(alarm.getMsg())) {
				dmfMsg = dmfMsg + alarm.getMsg();
			}
		}
		rowsCounts = dmfMsg.split("\n\t").length;
	}

	private void getAllUnboundEquipmentNames(String stationId) {
		equipmentNames.clear();
		Set<String> strSet = new HashSet<String>();
		List<CfgAnalogChannel> byWaVeId1 = cfgMan.listCfgAnalogChannelsBySubId(stationId);
		List<CfgDigitalChannel> byWaVeId2 = cfgMan.listCfgDigitalChannelsBySubId(stationId);
		for (CfgAnalogChannel channel : byWaVeId1) {
			strSet.add(channel.getEquipmentId());
		}
		for (CfgDigitalChannel channel : byWaVeId2) {
			strSet.add(channel.getEquipmentId());
		}
		List<ACLineSegment> acLines = manager.getAcLineSegmentsBySubstation(stationId);
		List<PowerTransformer> powers = manager.getPowerTransformersByStationId(stationId);
		List<BusbarSection> busbars = manager.getBusbarSectionsByStationId(stationId);
		List<Breaker> breakers = manager.getBreakersByStationId(stationId);
		List<HydroGeneratingUnit> hydros = manager.getHydroGeneratingUnitsByStationId(stationId);
		List<Compensator> compens = manager.getCompensatorsByStationId(stationId);
		List<GeneratingUnit> genes = manager.getGeneratingUnitsByStationId(stationId);
		List<TransformerWinding> windings = manager.getTransformerWindingsByStationId(stationId);
		for (ACLineSegment acline : acLines) {
			if (!strSet.contains(acline.getId())) {
				equipmentNames.add(acline.getName());
			}
		}
		for (PowerTransformer power : powers) {
			if (!strSet.contains(power.getId())) {
				equipmentNames.add(power.getName());
			}
		}
		for (BusbarSection busbar : busbars) {
			if (!strSet.contains(busbar.getId())) {
				equipmentNames.add(busbar.getName());
			}
		}
		for (Breaker breaker : breakers) {
			if (!strSet.contains(breaker.getId())) {
				equipmentNames.add(breaker.getName());
			}
		}
		for (HydroGeneratingUnit hydro : hydros) {
			if (!strSet.contains(hydro.getId())) {
				equipmentNames.add(hydro.getName());
			}
		}
		for (Compensator compen : compens) {
			if (!strSet.contains(compen.getId())) {
				equipmentNames.add(compen.getName());
			}
		}
		for (GeneratingUnit gen : genes) {
			if (!strSet.contains(gen.getId())) {
				equipmentNames.add(gen.getName());
			}
		}
		for (TransformerWinding winding : windings) {
			if (!strSet.contains(winding.getId())) {
				equipmentNames.add(winding.getName());
			}
		}
	}

	public List<String> completeEquipmentNames(String query) {
		List<String> results = new ArrayList<String>();
		for (String s : digitRelateDevice.keySet()) {
			if (s.startsWith(query))
				results.addAll(digitRelateDevice.get(s));
		}
		return results;
	}

	// 模拟通道关联设备
	public void getEquipmentByStation() {
		Map<String, Object> options = new HashMap<String, Object>();
		options.put("resizable", true);
		options.put("draggable", true);
		// options.put("responsive", true);
		options.put("modal", false);
		options.put("width", 600);
		options.put("height", 400);
		Map<String, List<String>> params = new HashMap<>();
		List<String> s = new ArrayList<>();
		s.add(stationId);
		params.put("stationId", s);
		openDialog("/ui/common/equipment_selector_single",
				params, options);
	}

	// 还需完善
	private int getEquipType(Object object) {
		if (object instanceof ACLineSegment) {
			return CfgChnsParserUtil.TYPE_LINE;
		} else if (object instanceof BusbarSection) {
			return CfgChnsParserUtil.TYPE_BUSBAR;
		} else if (object instanceof Breaker) {
			return CfgChnsParserUtil.TYPE_BREAKER;
		} else if (object instanceof ProtectionEquipment) {
			return CfgChnsParserUtil.TYPE_PROTECT;
		} else if (object instanceof PowerTransformer) {
			return CfgChnsParserUtil.TYPE_POWER;
		} else if (object instanceof Compensator) {
			return CfgChnsParserUtil.TYPE_COMPEN;
		} else if (object instanceof TransformerWinding) {
			return CfgChnsParserUtil.TYPE_POWER;
		}
		return 0;
	}

	public void onAnologSelectorChosen(SelectEvent event) {
		IdentifiedObject equipment = (IdentifiedObject) event.getObject();
		if (equipment != null) {
			for (CfgAnalogChannel channel : analogSelecteds) {
				channel.setEquipmentId(equipment.getId());
				channel.setEquipmentName(equipment.getName());
				channel.setEquipmentType(getEquipType(event.getObject()));
				cfgMan.saveCfgAnalogChannel(channel);
			}

			addSuccessMessage("保存成功");
		}
	}

	public void onDigitSelectorChosen(SelectEvent event) {
		IdentifiedObject equipment = (IdentifiedObject) event.getObject();
		for (CfgDigitalChannel channel : digitSelecteds) {
			channel.setEquipmentId(equipment.getId());
			channel.setEquipmentName(equipment.getName());
			channel.setEquipmentType(getEquipType(event.getObject()));
			cfgMan.saveCfgDigitalChannelChannel(channel);
		}
		addSuccessMessage("保存成功");
	}

	/*
	 * public void update(String flag){
	 * if((flag.equals("anolog"))&&(analogSelected!=null)){
	 * //dao.update(analogSelected, CfgAnalogChannel.class);
	 * addSuccessMessage("保存成功"); }else
	 * if((flag.equals("digit"))&&(digitSelected!=null)){
	 * //dao.update(digitSelected, CfgDigitalChannel.class);
	 * addSuccessMessage("保存成功"); }else{ addErrorMessage("保存失败"); }
	 *
	 * }
	 */
	public void getDigitEquipmentByStation() {
		// 断路器
		List<Breaker> breakers = manager.getBreakersByStationId(stationId);
		// 保护
		List<ProtectionEquipment> protects = manager.getProtectionEquipmentsByStationId(stationId);
		for (Breaker r : breakers) {
			String key = PingYinUtil.getPingYinHeader(r.getName());
			List<String> ss = digitRelateDevice.get(key);
			if (ss == null) {
				ss = new ArrayList<>();
				digitRelateDevice.put(key, ss);
			}
			ss.add(r.getName());
		}
		for (ProtectionEquipment r : protects) {
			String key = PingYinUtil.getPingYinHeader(r.getName());
			List<String> ss = digitRelateDevice.get(key);
			if (ss == null) {
				ss = new ArrayList<>();
				digitRelateDevice.put(key, ss);
			}
			ss.add(r.getName());
		}
	}

	private void genSvgContent(String stationId) {
		StringBuffer sb = new StringBuffer();
		File sf = new File(pros.getSvgBxPath() + stationId + ".svg");
		if (sf.exists()) {
			RandomAccessFile raf = null;
			try {
				raf = new RandomAccessFile(sf, "r");
				String lstr = raf.readLine();
				boolean startAdd = false;
				while (lstr != null) {
					if (startAdd) {
						lstr = new String(lstr.trim().getBytes("ISO-8859-1"), "utf-8");
						lstr = lstr.replaceAll("\"", "'");
						sb.append(lstr);
					} else {
						if (lstr.startsWith("<svg")) {
							startAdd = true;
							lstr = new String(lstr.trim().getBytes("ISO-8859-1"), "utf-8");
							lstr = lstr.replaceAll("\"", "'");
							sb.append(lstr);
						}
					}
					lstr = raf.readLine();
				}
				svgContent = sb.toString();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					raf.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		} else {
			svgContent = "";
		}
	}

	public void autoCompleteStation(SelectEvent event) {
		Object item = event.getObject();
		if (null != item) {
			filterTree(item.toString());
		}
	}

	public void resetUploadedFileMap() {
		uploadFileMap.clear();
	}

	/**
	 * 上传录波文件 由于这个方法是多线程调用uploadedFileList使用线程安全的集合
	 *
	 * @param event
	 */
	public void handleWaveFileUpload(FileUploadEvent event) {
		UploadedFile uf = event.getFile();
		String fileName = uf.getFileName();
		uploadFileMap.put(fileName, uf.getContents());
		if ( uploadFileMap.size() == 2) {
			String stationPrivateId = selectedWaveEquipment.getStationPrivateId();
			String equipment = selectedWaveEquipment.getId();
			String dirPath = pros.getWaveFilePath() + stationPrivateId + File.separator + equipment
					+ File.separator;
			int status = -1;
			try {
				status = waveFilemanager.saveWaveFileAndGenerateRecord(selectedWaveEquipment, dirPath,
						uploadFileMap);
				getWaveChannelInfo(selectedWaveEquipment.getId());
				getMsgs(selectedWaveEquipment.getId());
				waveFiles = waveFilemanager.listWaveFiles(selectedWaveEquipment.getId());
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (status == 0)
				addSuccessMessage(fileName + "上传成功");
			else if (status == -1)
				addErrorMessage("上传文件列表存在异常");
			else if (status == 1)
				addErrorMessage("发生IO异常请联系管理员，谢谢");
			else
				addErrorMessage("发生未知异常");
		}

	}

	public void deleteWaveFile(String id) {
		WaveFile w = waveFilemanager.getWaveFileById(id);
		String path = pros.getWaveFilePath() + w.getPath();
		File f1 = new File(path + ".cfg");
		if (f1.isFile() && f1.exists())
			f1.delete();
		File f2 = new File(path + ".dat");
		if (f2.isFile() && f2.exists())
			f2.delete();
		waveFiles.remove(w);
		waveFilemanager.deleteWaveFileById(id);
		addSuccessMessage("删除成功！");
	}

	public void reSetFileStatus(String id) {
		waveFilemanager.resetWaveFileStatus(id);
		addSuccessMessage("已经重新解析，请等待！");
	}

	public void deleteWaveEquipment() {

		if (selectWaveEquipment != null) {
			weManager.deleteWaveEquipmentById(selectWaveEquipment);
			Iterator<TreeNode> it = currentSelect.getChildren().iterator();
			while (it.hasNext()) {
				TreeNode node = it.next();
				if (((IdentifiedObject) node.getData()).getId().equals(selectWaveEquipment.getId())) {
					it.remove();
					break;
				}
			}
			waveEquipments.remove(selectWaveEquipment);
			cfgMan.deleteCfgChannelByWaVeId(waveId);
			addSuccessMessage("删除成功!");
			selectWaveEquipment = null;
		} else {
			addErrorMessage("请选择要删除的数据！");
		}
	}

	public void preCreateWaveEquipment() {
		preWaveEquipment = new WaveEquipment();
	}

	public void saveWaveEquipment() {
		String err = null;
		if (preWaveEquipment.getId() == null) {
			String sid = ((IdentifiedObject) currentSelect.getData()).getId();
			preWaveEquipment.setSubId(sid);
			BxSubstation bxs = bxcim.findStationByCimId(sid);
			if (bxs != null) {
				preWaveEquipment.setStationPrivateId(bxs.getStationid());
				try {
					preWaveEquipment.setCfg(cfgMan.getWaveCfgConent(preWaveEquipment));
				} catch (Exception e) {
					// addErrorMessage(e.getMessage());
					err = "cfg文件不存在！";
				}
			} else {
				// 如果没有这个录波器则自动生成一个privateStationId
				preWaveEquipment.setStationPrivateId(ObjectId.get().toString());
			}
			preWaveEquipment.setSubName(((IdentifiedObject) currentSelect.getData()).getName());
			preWaveEquipment = weManager.saveWaveEquipment(preWaveEquipment);
			new LibTreeNode("wave", preWaveEquipment, currentSelect);
			waveEquipments.add(preWaveEquipment);
		} else {
			preWaveEquipment = weManager.saveWaveEquipment(preWaveEquipment);
			List<TreeNode> nodes = currentSelect.getChildren();
			for (int i = 0; i < nodes.size(); i++) {
				if (((IdentifiedObject) nodes.get(i).getData()).getId().equals(preWaveEquipment.getId())) {
					currentSelect.getChildren().set(i, new DefaultTreeNode("wave", preWaveEquipment, null));
					break;
				}
			}
			for (int i = 0; i < waveEquipments.size(); i++) {
				if (waveEquipments.get(i).getId().equals(preWaveEquipment.getId())) {
					waveEquipments.set(i, preWaveEquipment);
					break;
				}
			}
		}
		preWaveEquipment = new WaveEquipment();
		if (err == null) {
			addSuccessMessage("保存成功!");
		} else {
			addErrorMessage(err);
		}
	}

	public void editWaveEquipment() {
		preWaveEquipment = selectWaveEquipment;
	}

	public void editAnologInfo() {
		if (analogSelecteds != null && analogSelecteds.size() > 0)
			analogSelected = analogSelecteds.get(0);
	}

	public void saveAnologInfo() {
		cfgMan.saveCfgAnalogChannel(analogSelected);
		for (int i = 0; i < anologInfo.size(); i++) {
			if (anologInfo.get(i).getId().equals(analogSelected.getId())) {
				anologInfo.set(i, analogSelected);
				break;
			}
		}
		addSuccessMessage("保存成功！");
		selectWaveEquipment = null;
	}

	public void editDigitInfo() {
		if (digitSelecteds != null && digitSelecteds.size() > 0) {
			digitSelected = digitSelecteds.get(0);
		}
	}

	public void saveCfgDigitalChannel() {
		cfgMan.saveCfgDigitalChannelChannel(digitSelected);
		for (int i = 0; i < digitInfo.size(); i++) {
			if (digitInfo.get(i).getId().equals(digitSelected.getId())) {
				digitInfo.set(i, digitSelected);
				break;
			}
		}
		addSuccessMessage("保存成功！");
	}

	public String seeDmf(String str) {
		if (StringUtils.isEmpty(str)) {
			str = "dmf 信 息 为 空";
		}
		return str;
	}

	public String getFileName(String filePath) {
		String rtn = "";
		if (StringUtils.isEmpty(filePath)) {
			return rtn;
		}
		int pos = filePath.lastIndexOf("/");
		if (pos > -1) {
			rtn = filePath.substring(pos + 1, filePath.length());
		}
		return rtn;
	}

	public void prepareDownload(WaveFile wf) {
		FileInputStream fis = null;
		try {
			fis = wfam.generateDownloadZipFile(wf);
			file = new DefaultStreamedContent(fis, "application/octet-stream", wf.getEquipment() + ".zip") ;
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		if(file == null) {
			addErrorMessage("查找文件失败，无法下载");
		}
	}

	public TreeNode getRoot() {
		return root;
	}

	public void setRoot(TreeNode root) {
		this.root = root;
	}

	public TreeNode getCurrentSelect() {
		return currentSelect;
	}

	public void setCurrentSelect(TreeNode currentSelect) {
		this.currentSelect = currentSelect;
	}

	public String getFilterStation() {
		return filterStation;
	}

	public void setFilterStation(String filterStation) {
		this.filterStation = filterStation;
	}

	public String getSvgContent() {
		return svgContent;
	}

	public void setSvgContent(String svgContent) {
		this.svgContent = svgContent;
	}

	public List<CfgAnalogChannel> getAnologInfo() {
		return anologInfo;
	}

	public void setAnologInfo(List<CfgAnalogChannel> anologInfo) {
		this.anologInfo = anologInfo;
	}

	public List<CfgDigitalChannel> getDigitInfo() {
		return digitInfo;
	}

	public void setDigitInfo(List<CfgDigitalChannel> digitInfo) {
		this.digitInfo = digitInfo;
	}

	public CfgAnalogChannel getCa() {
		return ca;
	}

	public void setCa(CfgAnalogChannel ca) {
		this.ca = ca;
	}

	public CfgDigitalChannel getCd() {
		return cd;
	}

	public void setCd(CfgDigitalChannel cd) {
		this.cd = cd;
	}

	public CfgAnalogChannel getAnalogSelected() {
		return analogSelected;
	}

	public void setAnalogSelected(CfgAnalogChannel analogSelected) {
		this.analogSelected = analogSelected;
	}

	public CfgDigitalChannel getDigitSelected() {
		return digitSelected;
	}

	public void setDigitSelected(CfgDigitalChannel digitSelected) {
		this.digitSelected = digitSelected;
	}

	public Map<String, List<String>> getDigitRelateDevice() {
		return digitRelateDevice;
	}

	public void setDigitRelateDevice(Map<String, List<String>> digitRelateDevice) {
		this.digitRelateDevice = digitRelateDevice;
	}

	public List<String> getEquipmentNames() {
		return equipmentNames;
	}

	public void setEquipmentNames(List<String> equipmentNames) {
		this.equipmentNames = equipmentNames;
	}

	public List<WaveFile> getWaveFiles() {
		return waveFiles;
	}

	public void setWaveFiles(List<WaveFile> waveFiles) {
		this.waveFiles = waveFiles;
	}

	public String getDmfMsg() {
		return dmfMsg;
	}

	public void setDmfMsg(String dmfMsg) {
		this.dmfMsg = dmfMsg;
	}

	public List<WaveEquipment> getWaveEquipments() {
		return waveEquipments;
	}

	public void setWaveEquipments(List<WaveEquipment> waveEquipments) {
		this.waveEquipments = waveEquipments;
	}

	public WaveEquipment getSelectWaveEquipment() {
		return selectWaveEquipment;
	}

	public void setSelectWaveEquipment(WaveEquipment selectWaveEquipment) {
		this.selectWaveEquipment = selectWaveEquipment;
	}

	public WaveEquipment getPreWaveEquipment() {
		return preWaveEquipment;
	}

	public void setPreWaveEquipment(WaveEquipment preWaveEquipment) {
		this.preWaveEquipment = preWaveEquipment;
	}

	public int getRowsCounts() {
		return rowsCounts;
	}

	public void setRowsCounts(int rowsCounts) {
		this.rowsCounts = rowsCounts;
	}

	public List<CfgAnalogChannel> getAnalogSelecteds() {
		return analogSelecteds;
	}

	public void setAnalogSelecteds(List<CfgAnalogChannel> analogSelecteds) {
		this.analogSelecteds = analogSelecteds;
	}

	public List<CfgDigitalChannel> getDigitSelecteds() {
		return digitSelecteds;
	}

	public void setDigitSelecteds(List<CfgDigitalChannel> digitSelecteds) {
		this.digitSelecteds = digitSelecteds;
	}

	public WaveEquipment getSelectedWaveEquipment() {
		return selectedWaveEquipment;
	}

	public void setSelectedWaveEquipment(WaveEquipment selectedWaveEquipment) {
		this.selectedWaveEquipment = selectedWaveEquipment;
	}

	public StreamedContent getFile() {
		return file;
	}

	public void setFile(StreamedContent file) {
		this.file = file;
	}

	public int getVoltage() {
		return voltage;
	}

	public void setVoltage(int voltage) {
		this.voltage = voltage;
	}

}
